//
//  ST_TianChallengeController.swift
//  btvideo
//
//  Created by mac on 2021/6/22.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//
import UIKit
import SwifterSwift
import SnapKit
import WebKit
import SwiftyJSON
import WKWebViewJavascriptBridge
import RxSwift
import RxCocoa


class ST_TianChallengeController: UIViewController,  WKNavigationDelegate {
    
    var webView = WKWebView()
    
    lazy var bridge = WKWebViewJavascriptBridge(webView: webView)
    
    var urlStr:String = SCComponets.rich_text_storage_component.json["ai_my_center"]["url_2"].stringValue
    
    var titleStr = SCComponets.rich_text_storage_component.json["ai_my_center"]["title"].stringValue
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = Color.white
        webView.backgroundColor = Color.clear
        webView.isOpaque = false
        webView.navigationDelegate = self
        
        set_up_view()
        
        request()
        
        self.view.addSubview(webView)
        let line = UIView()
        line.backgroundColor = Color.init(hex: 0x999999, transparency: 0.3)
        self.view.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.top.equalTo(back_btn.snp.bottom).offset(5)
            make.left.right.equalTo(self.view)
            make.height.equalTo(1)
        }
        webView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(line.snp.bottom)
        }
        
        
        bridge.register(handlerName: "NativeApi_getUserData") { (paramters, callback) in
            
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            let keys = jsCall["keys"].stringValue.components(separatedBy: ",")
            
            var result = [String:Any]()
            
            for item in  keys{
                
                if let value = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.value(forKey: item){
                    result.updateValue(value, forKey: item)
                }else{
                    result.updateValue("", forKey: item)
                }
            }
            
            result.updateValue("1", forKey: "version")
            
            if let json = JSON(dictionary: result){
             
                callback?(json.rawString() ?? "")
                
            }
        }
        
        bridge.register(handlerName: "NativeApi_net") { (paramters, callback) in
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            let requestBody = jsCall["data"].dictionaryObject
            
            JVrequest(PH.outside_widget_url(component: jsCall["url"].stringValue),parameters: requestBody) { (json) in
            
                print("外包--后台返回数据",json)
                
                callback?(json.rawString() ?? "")
                
            } failure: { (code, err) in
             
                
            }
            print("外包--iOSCallback called 接口: \(String(describing: paramters))")
        }
        
        
        bridge.register(handlerName: "NativeApi_copyToPasteboard") { (paramters, callback) in
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            jsCall["str"].stringValue.copyToPasteboard()
            
        }
        
        
        
        bridge.register(handlerName: "NativeApi_share") {[weak self] (paramters, callback) in
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            self?.share(url: jsCall["url"].stringValue)
            
            
            callback?("Response success")
            
        }
        
        
        
        bridge.register(handlerName: "NativeApi_bindZFB") {[weak self] (paramters, callback) in
            
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            self?.bind_z_l_b(url: jsCall["url"].stringValue)
            
            callback?("Response success")
            
        }
//
        URLCache.shared.removeAllCachedResponses()
        
        if let url = URL.init(string: urlStr){
            webView.load(URLRequest(url: url))
        }
        
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    var disposeBag = DisposeBag()
    
    fileprivate var otherData = JSON.null
    
    fileprivate func request(){
        
        JVrequest(PH.outsideIncomeLogEntityApi) { (json) in
            
            self.otherData = json["data"]
            
            self.right_nav_btn.setTitleForAllStates(self.otherData["pd_zz_history"].stringValue)
            
        } failure: { (code, err) in
            
        }

        
        
    }
    
    
    func set_up_view(){
   
        self.view.addSubview(navi_view)
        self.view.addSubview(back_btn)
        self.view.addSubview(titleLabel)
        self.view.addSubview(right_nav_btn)
        
        
        navi_view.snp.makeConstraints { (make ) in
            make.left.right.top.equalTo(self.view)
            
            make.height.equalTo(navigationBarHeight + statusBarHeight)
        }
        
        back_btn.snp.makeConstraints { (make ) in
            make.top.equalTo(self.view).offset(statusBarHeight)
            make.left.equalTo(self.view).offset(8)
            make.width.height.equalTo(44)
        }
        titleLabel.snp.makeConstraints { (make ) in
            make.centerY.equalTo(back_btn)
            make.centerX.equalTo(self.view)
            make.height.equalTo(25)
        }
        
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(navi_view).offset(-20)
            make.bottom.equalTo(navi_view)
            make.height.equalTo(44)
        }
    }
    lazy var navi_view : UIView = {
        let view = UIView()
        view.backgroundColor = Color.white
        return view
    }()
    lazy var back_btn:UIButton = {
        let btn = UIButton()
        
        btn.setImageForAllStates(ST_ImageUtils.imageName("返回_gray")!)
        btn.addTarget(self, action: #selector(back_action(sender: )), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var titleLabel:UILabel = {
        let control = UILabel()
        
        control.textColor = Color.black
        control.font = UIFont.systemFont(ofSize: 18)
        
        control.text = titleStr
        return control
    }()

    lazy var right_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        //        control.cornerRadius = 18
         
        control.setTitleColorForAllStates(Color.init(hexString: "#EE940C")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        control.addTarget(self, action: #selector(right_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    // MARK: - delegate
//    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//
//        if let title = webView.title{
//            self.titleLabel.text = title
//        }
//
//    }
}

extension ST_TianChallengeController{
    
    @objc func back_action(sender: UIButton) {
        goback_previous_controller()
    }
    
   
    @objc func right_click() {
        
        let vc = ST_TianChallengeHistoryController()
        
        vc.title = otherData["pd_zz_history"].stringValue
        
        self.navigationController?.pushViewController(vc)
    }
    
    func push_zff(){
        
        let vc = ST_ConversionInputViewController()
        
        vc.pd_Name = self.otherData["pd_zz_name"].stringValue
        
        vc.append_closure = {[weak self] _ in
            
            self?.bridge.call(handlerName: "JsApi_refreshWeb", data: ["foo": "before ready"], callback: nil)
            
        }
        
        self.navigationController?.pushViewController(vc)
        
    }
    /// 绑定众乐帮
    func bind_z_l_b(url:String){
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = url
        
        vc.goback_publisher.subscribe(onNext:{[weak self] in
            
            print("绑定支付之后刷新H5")
            
            self?.bridge.call(handlerName: "JsApi_refreshWeb", data: ["foo": "before ready"], callback: nil)
            
        }).disposed(by: disposeBag)
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func share(url:String){
        
        let type = url.last?.string ?? ""
        
        let title = self.otherData["share_title_"+type].stringValue
        
        let content = self.otherData["share_content_"+type].stringValue
        
        let vc = ST_ShareMyAppController()
        
        vc.share_data = ST_ShareViewStruct(url: "http://t.jingniaoapps.com"+url, icon: "http://btstatic.jingniaoapps.com/WechatIMG16.png", title: title, content: content)
        
        vc.overCurrentContext = true
        
        GlobalPresent(toController: vc)
        
    }
    
}


//MARK:- Extension
extension ST_BTVideoURLDispatcher{
    
    /// 拼接URL
    func outside_widget_url(component:String) -> String {
        
        var myString = component
        
        myString.remove(at: myString.startIndex)
        
        return String.BTappendUrl(str: myString)
    }
    
}
